<!--
 选择区域
-->
<template>
  <div class="flow-select-tree-box flow-table-box">
    <div class="search-box">
      <a-select
        v-if="type !== 'user'"
        v-model:value="selectOptionId"
        :placeholder="'请选择' + placeholderMap[type]"
        style="width: 150px; margin-right: 4px; flex-shrink: 0"
        :show-search="true"
        :filter-option="filterOption"
        allow-clear
        @change="handleChange"
      >
        <a-select-option v-for="item in treeData" :key="item.id" :value="item.id" :title="item.title">
          {{ item.title }}
        </a-select-option>
      </a-select>
      <a-input-search v-model:value="searchText" allow-clear placeholder="请输入姓名或登录名检索" @search="handleKeyWordQuery" />
    </div>
    <div class="select-role-box" style="height: calc(100% - 42px)">
      <s-table
        v-model:pagination="pagination"
        row-key="key"
        :loading="tableLoading"
        :row-height="36"
        :height="236"
        :bordered="false"
        :show-header="false"
        :columns="columns"
        :data-source="tableList"
        :range-selection="false"
        :row-selection="{
          type: checkable ? 'checkbox' : 'radio',
          selectedRowKeys: selectedRowKeys,
          onSelect: onSelectChange,
          columnWidth: checkable ? 32 : 0
        }"
        :custom-row="
          (record) => {
            return {
              onClick: () => {
                handleRowSelection(record);
              }
            };
          }
        "
        @change="handleTableChange"
      >
        <template #bodyCell="{ record }">
          <div style="display: flex; align-items: center">
            <span class="user-icon">
              <avic-icon svg="avic-account-circle-fill" color="#3370ff" />
            </span>
            <span class="cell-txt" :title="record['title']">
              <span>{{ record['title'] }}</span>
              <span v-if="showMoreUserInfo" style="color: #86909c">
                <slot name="moreInfo" :user-side-info="record.attributes">
                  {{ getAttributes(record) }}
                </slot>
              </span>
            </span>
          </div>
        </template>
      </s-table>
      <div v-if="checkable" class="pagination-box">
        <a-checkbox
          v-model:checked="state.checkAll"
          :indeterminate="selectedRowKeys.length > 0 && selectedRowKeys.length < tableList.length"
          @change="handleCheckAllChange"
        />
      </div>
    </div>
  </div>
</template>
<!-- eslint-disable max-lines -->
<script>
import { setUserList } from './_util';
import request from '@/utils/request';
import { listCommonSelectUserByPage } from './api';
export default {
  name: 'SelectTable',
  props: {
    type: {
      type: String,
      required: true,
      default: 'role'
    },
    // prop接收传过来的参数
    select: {
      type: Object,
      required: true // 校验
    },
    data: {
      type: Object,
      required: true, // 校验
      default: null
    },
    selectAll: {
      type: String,
      required: false, // 校验
      default: ''
    },
    formId: {
      type: String,
      required: false, // 校验
      default: ''
    },
    visible: {
      type: Boolean,
      required: false,
      default: false
    },
    buttonData: {
      required: false,
      type: Object,
      default: null
    },
    // 流程实例
    bpmInstanceObject: {
      type: Object,
      default: null
    },
    defaultSelectedUser: {
      type: Array,
      required: true,
      default: () => []
    },
    showMoreUserInfo: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      selectUser: [], // 选中的用户
      noChange: false,
      searchList: [],
      userList: [],
      treeCheckedKeys: [],
      treeSelectedKeys: [],
      expandedKeys: [],
      treeData: [],
      defaultMaxParentId: '-1',
      initTreeData: [], // 初始化加载树数据
      tableRefName: 'userListTable',
      treeRefName: 'avicTreeElement',
      deptUrl: '/bpm/bpmActor/bpmSelectUserAction2/dept/v1', // 部门树访问地址
      positionUrl: '/bpm/bpmActor/bpmSelectUserAction2/position/v1', // 岗位树访问地址
      groupUrl: '/bpm/bpmActor/bpmSelectUserAction2/group/v1', // 群组树访问地址
      roleUrl: '/bpm/bpmActor/bpmSelectUserAction2/role/v1', // 角色树访问地址
      selectFlowTab: 0, // 当前选中的流程页签
      selectTag: '', // 当前选人的纬度类型
      // 树组件需要的加载数据格式
      tableParam: {
        url: '',
        parameter: {
          checked: false
        },
        method: 'post'
      },
      // 树搜索组件需要的加载数据格式
      searchTreeParam: {
        url: '/bpm/bpmActor/bpmSelectUserAction2/getSearchUsersJSONData/v1',
        parameter: {},
        method: 'post'
      },
      isSwitch: false,
      searchText: '',
      checkable: true, // 是否多选
      scopedSlots: { title: 'title' }, // 树收藏
      menuList: [],
      menuVisible: false,
      addCommonContactUrl: '/bpm/bpmActor/bpmSelectUserAction2/addCommonContact/v1',
      delCommonContactUrl: '/bpm/bpmActor/bpmSelectUserAction2/delCommonContact/v1',
      rightNode: null,
      roleSpinning: false,
      treeNodeDataRef: {}, // 当前节点信息
      loading: false, // bigtree loading
      selectListMap: {}, // bigtree 选中的用户
      expandLevel: '1', // 展开层级
      emptyText: '暂无数据', // 搜索为空时的提示数据
      treeLoadedKeys: [],
      needCheckedKeys: [], // 需要选中的节点记录
      placeholderMap: {
        role: '角色',
        group: '群组',
        position: '岗位'
      },
      selectOptionId: null, // 下拉框选中的id
      selectOption: null, // 下拉框选中对象
      columns: [
        {
          title: '名称',
          dataIndex: 'title',
          key: 'id'
        }
      ],
      tableList: [],
      tableLoading: false, // 表格加载状态
      selectedRowKeys: [],
      pagination: {
        size: 'small',
        current: 1,
        pageSize: 20,
        // s-table组件内部的defaultPageSize与指定的pageSize不一致时，会在初始化时触发一次change事件，导致重复请求
        defaultPageSize: 20,
        total: 0,
        showLessItems: true, // showQuickJumper: true,
        showSizeChanger: true,
        position: ['bottomCenter']
      },
      queryParam: {
        // 请求表格数据参数
        pageParameter: {
          page: 1, // 页数
          rows: 20 // 每页条数
        },
        searchParams: {
          searchText: ''
        }
      },
      state: { indeterminate: true, checkAll: false } // 全选
    };
  },
  /** 参数 select {selectFlowTab:3 当前激活的分支节点页签, selectTag:"user" 节点可选择的维度} */
  watch: {
    select: {
      immediate: true,
      handler(newV) {
        if (
          newV &&
          newV.selectTag &&
          newV.selectFlowTab > -1 &&
          (newV.selectTag !== this.selectTag || newV.selectFlowTab !== this.selectFlowTab)
        ) {
          this.selectFlowTab = newV.selectFlowTab; // 记录当前激活的分支页签
          if (newV.selectTag !== this.type) {
            return;
          }
          if (newV.selectTag !== this.selectTag) {
            this.isSwitch = true; // 标记为新切换的 选人维度
          }
          this.searchText = '';
          this.selectTag = newV.selectTag; // 记录当前 选人维度
          this.initTable();
          console.log('this.selectTag', this.selectTag);
          this.setDefaultSelectUser(this.defaultSelectedUser);
        }
      }
    }
  },
  methods: {
    /** 初始化列表 */
    initTable() {
      if (this.loading) {
        return;
      }
      if (this.selectTag && this.selectFlowTab > -1) {
        this.initTableUrl(); // 初始化请求参数
        this.initTableData(); // 初始化数据
      }
    },
    /** 1.初始化查询路径url */
    initTableUrl() {
      if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].currentActivityAttr) {
        if (
          this.data.nextTask[this.selectFlowTab].currentActivityAttr.dealType === '1' ||
          this.data.nextTask[this.selectFlowTab].currentActivityAttr.single === 'yes'
        ) {
          // 单选用户
          this.checkable = false;
        } else {
          this.checkable = true;
        }
      }
      if (this.selectTag !== 'user') {
        const para = [];
        let list = '';
        let nodeType = '';
        if (this.selectTag === 'orgDept') {
          if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].orgList.length > 0) {
            list = 'orgList'; // 组织
            nodeType = 'rootOrg';
          } else if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].deptList.length > 0) {
            list = 'deptList'; // 部门
            nodeType = 'root';
          }
          this.tableParam.url = this.data.orgDeptTreeUrl ? this.data.orgDeptTreeUrl : this.deptUrl;
        } else if (this.selectTag === 'role') {
          list = 'roleList';
          nodeType = this.selectTag;
          this.tableParam.url = this.data.roleTreeUrl ? this.data.roleTreeUrl : this.roleUrl;
        } else if (this.selectTag === 'group') {
          list = 'groupList';
          nodeType = this.selectTag;
          this.tableParam.url = this.data.groupTreeUrl ? this.data.groupTreeUrl : this.groupUrl;
        } else if (this.selectTag === 'position') {
          list = 'positionList';
          nodeType = this.selectTag;
          this.tableParam.url = this.data.positionTreeUrl ? this.data.positionTreeUrl : this.positionUrl;
        }
        if (
          this.data.nextTask &&
          list !== '' &&
          this.data.nextTask[this.selectFlowTab][list] &&
          this.data.nextTask[this.selectFlowTab][list].length > 0
        ) {
          this.data.nextTask[this.selectFlowTab][list].forEach((tim) => {
            para.push(tim.id);
          });
        }
        const buttonData = this.getButtonData();
        if (this.selectTag === 'role') {
          this.setParameter(para, buttonData);
        } else {
          this.tableParam.parameter = {
            nodeType,
            para: JSON.stringify(para),
            filterUser: this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || '',
            secretLevel: this.data.secretLevel,
            formId: this.formId,
            executionId: buttonData.buttonData.executionId,
            processInstanceId: buttonData.buttonData.processInstanceId,
            taskId: buttonData.buttonData.taskId
          };
        }
      }
    },
    /*
        获取流程参数
    */
    getButtonData() {
      if (this.visible) {
        return { buttonData: this.buttonData, submitFuncName: '' };
      }
      return this.bpmInstanceObject.bpmCommonSelect;
    },
    /*
        2. bigtree 初始化数据
    */
    async initTableData() {
      this.initTreeData = [];
      this.expandedKeys = [];
      this.treeLoadedKeys = [];
      let treeData = [];
      if (this.selectTag === 'role') {
        if (this.data.currentActivityAttr?.cfSelectUser === 'true') {
          // 成飞复杂角色树
          this.$emit('loading', true);

          const result = await this.getRole();
          if (result.success) {
            treeData = result.result;
            this.processInitRole(treeData);
          }
          this.$emit('loading', false);
        } else {
          // 平台正常角色树
          if (this.data.roleTreeZNode && this.data.roleTreeZNode.length > 0) {
            treeData = this.data.roleTreeZNode;
          } else {
            if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].roleList.length > 0) {
              treeData = this.processTreeData(this.data.nextTask[this.selectFlowTab].roleList);
            }
          }
        }
      } else if (this.selectTag === 'user') {
        if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].userList.length > 0) {
          treeData = setUserList(this.data.nextTask[this.selectFlowTab].userList, this.checkable);
        }
      } else if (this.selectTag === 'model') {
        if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].modelList.length > 0) {
          treeData = this.processTreeData(this.data.nextTask[this.selectFlowTab].modelList);
        }
      } else if (this.selectTag === 'group') {
        if (this.data.groupTreeZNode && this.data.groupTreeZNode.length > 0) {
          treeData = this.data.groupTreeZNode;
        } else {
          if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].groupList.length > 0) {
            treeData = this.processTreeData(this.data.nextTask[this.selectFlowTab].groupList);
          }
        }
      } else if (this.selectTag === 'position') {
        if (this.data.positionTreeZNode && this.data.positionTreeZNode.length > 0) {
          treeData = this.data.positionTreeZNode;
        } else {
          if (this.data.nextTask && this.data.nextTask[this.selectFlowTab].positionList.length > 0) {
            treeData = this.processTreeData(this.data.nextTask[this.selectFlowTab].positionList);
          }
        }
      }
      this.treeData = [...treeData];
      if (this.selectTag === 'user') {
        this.tableList = [...treeData];
        this.pagination.total = treeData.length;
      }
      // else {
      //   this.getUserList();
      // }
    },
    /**
     * 设置参数---CF流程自定义选人方案
     */
    setParameter(para, buttonData) {
      if (this.data.currentActivityAttr?.cfSelectUser === 'true') {
        // CF复杂角色树
        let toActivityName = '';
        if (this.buttonData && this.buttonData.targetActivityName) {
          toActivityName = this.buttonData.targetActivityName;
        } else if (this.data.nextTask.length > 0) {
          toActivityName = this.data.nextTask[0].currentActivityAttr.activityName;
        }
        let deptImpl = '';
        if (this.data.nextTask.length > 0 && this.data.nextTask[0].currentActivityAttr.deptImpl) {
          deptImpl = this.data.nextTask[0].currentActivityAttr.deptImpl;
        }
        this.tableParam.parameter = {
          nodeType: '',
          para: '',
          roleIds: para.join(','),
          procInstId: buttonData.buttonData.processInstanceId,
          fromActivityName: this.data.currentActivityAttr.activityName ? this.data.currentActivityAttr.activityName : '',
          toActivityName,
          deptImpl,
          processKey: this.data.processKey ? this.data.processKey : '',
          filterUser: this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || '',
          secretLevel: this.data.secretLevel,
          formId: this.data.formId,
          executionId: buttonData.buttonData.executionId,
          taskId: buttonData.buttonData.taskId,
          id: ''
        };
      } else {
        // 平台正常角色树
        this.tableParam.parameter = {
          nodeType: 'role',
          id: buttonData.buttonData.id,
          para: JSON.stringify(para),
          filterUser: this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || '',
          secretLevel: this.data.secretLevel,
          formId: this.data.formId,
          checked: ''
        };
      }
    },
    /**
     * 异步获取角色树---成飞流程自定义选人方案
     */
    async getRole() {
      this.roleSpinning = true;
      const result = await request({
        url: this.roleUrl,
        data: this.tableParam.parameter,
        method: 'post'
      });
      return new Promise((resolve) => {
        this.roleSpinning = false;
        if (result.success) {
          resolve(result);
        } else {
          resolve(result);
        }
      });
    },
    /**
     * 角色节点处理 -- 成飞选人
     */
    processInitRole(tree) {
      if (tree && tree.length > 0) {
        tree.forEach((tim) => {
          if (tim.attributes.nodeType !== 'user') {
            tim.isLeaf = false;
            tim.disableCheckbox = false;
          }
          if (tim.children) {
            this.processInitRole(tim.children);
          }
        });
      }
    },
    /**
     * 搜索 1.点击搜索
     */
    onSearch(e) {
      if (e) {
        this.tableLoading = true;
        const searchCondition = this.getSearchCondition();
        let { selectTag } = this;
        if (selectTag === 'user') {
          selectTag = 'userList';
        }
        const paramDeptIds = '';
        const parameter = {
          searchContent: e,
          searchType: selectTag,
          searchCondition,
          paramDeptIds,
          secretLevel: this.data.secretLevel,
          filterUser: this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || ''
        };
        this.$emit('loading', true);
        request({
          url: this.searchTreeParam.url,
          data: parameter,
          method: this.searchTreeParam.method
        })
          .then((res) => {
            if (res.success) {
              if (res.data && res.data.length > 0) {
                this.setSearchList(res.data);
                this.treeData = [...this.searchList];
                this.tableList = [...this.searchList];
                this.pagination.total = res.data.length;
              } else {
                if (parameter.searchContent !== '') {
                  this.$message.warning(res.errorDesc || '未查询到匹配数据！');
                } else {
                  this.$message.warning('暂无数据！');
                }
              }
            }
            this.$emit('loading', false);
          })
          .catch(() => {
            this.$emit('loading', false);
          })
          .finally(() => {
            this.tableLoading = false;
          });
      } else {
        this.initTableData();
      }
    },
    /**
     * 搜索 step 2.拼接查询条件
     */
    getSearchCondition() {
      let conditionList = [];
      let nextTask = null;
      if (this.data.nextTask.length >= this.selectFlowTab) {
        nextTask = this.data.nextTask[this.selectFlowTab];
      }
      if (nextTask) {
        if (this.selectTag === 'user') {
          const condition = {};
          condition.processInstanceId = nextTask.currentActivityAttr.processInstanceId;
          condition.executionId = nextTask.currentActivityAttr.executionId;
          if (nextTask.currentActivityAttr.outcome == null || nextTask.currentActivityAttr.outcome === 'null') {
            condition.outcome = '';
          } else {
            condition.outcome = nextTask.currentActivityAttr.outcome;
          }

          condition.type = nextTask.currentActivityAttr.type;
          condition.targetActivityName = nextTask.currentActivityAttr.targetActivityName;
          condition.userId = nextTask.currentActivityAttr.userId;
          condition.taskId = nextTask.currentActivityAttr.taskId;
          condition.index = nextTask.currentActivityAttr.index;
          conditionList[0] = condition;
        } else if (this.selectTag === 'orgDept') {
          if (nextTask.orgList != null && nextTask.orgList.length && nextTask.orgList.length > 0) {
            for (let i = 0; i < nextTask.orgList.length; i++) {
              const orgInfo = {};
              orgInfo.id = nextTask.orgList[i].id;
              orgInfo.name = nextTask.orgList[i].name;
              orgInfo.type = 'org';
              conditionList.push(orgInfo);
            }
          } else {
            for (let i = 0; i < nextTask.deptList.length; i++) {
              const deptInfo = {};
              deptInfo.id = nextTask.deptList[i].id;
              deptInfo.name = nextTask.deptList[i].name;
              deptInfo.type = 'dept';
              conditionList.push(deptInfo);
            }
          }
        } else if (this.selectTag === 'role') {
          conditionList = nextTask.roleList;
        } else if (this.selectTag === 'model') {
          conditionList = nextTask.modelList;
        } else if (this.selectTag === 'group') {
          conditionList = nextTask.groupList;
        } else if (this.selectTag === 'position') {
          conditionList = nextTask.positionList;
        }
      }

      return JSON.stringify(conditionList);
    },
    /**
     * 搜索 step 3.缓存符合查询条件的数据
     */
    setSearchList(list) {
      const dataList = [];
      if (list && list.length > 0) {
        list.forEach((user) => {
          dataList.push({
            key: user.id || user.userId,
            attributes: {
              deptId: user.deptId,
              deptName: user.deptName,
              deptNamePath: user.deptNamePath,
              nodeType: 'user'
            },
            nodeType: 'user',
            isLeaf: true,
            title: user.userName,
            deptId: user.deptId,
            deptName: user.deptName,
            id: user.id || user.userId,
            name: user.userName,
            orderBy: user.orderBy
          });
        });
      }
      this.searchList = dataList;
    },
    /**
     * 切换选人事件 （父组件调用此方法回显已选人员）
     */
    changeSelectUser(list) {
      this.noChange = true;
      this.setDefaultSelectUser(list);
    },
    /**
     * 切换选人时 设置默认选中的user
     */
    setDefaultSelectUser(list) {
      if (list && list.length > 0) {
        let checkedKeys = [];
        this.selectListMap = {};
        list.forEach((tim) => {
          if (tim.selectFlowTab === this.selectFlowTab) {
            if (tim.users.length === 0) {
              checkedKeys = [];
            } else {
              tim.users.forEach((user) => {
                checkedKeys.push(user.key);
                this.selectListMap[user.id] = user; // 初始化listmap
              });
            }
          }
        });
        this.selectUser = [...list];
        this.setSelectedRowKeys();
        this.updateCheckboxState();
      }
    },
    // 删除节点
    deleteNode(node) {
      if (node.isLeaf) {
        delete this.selectListMap[node.id];
      } else if (node.children && node.children.length > 0) {
        node.children.forEach((tim) => {
          this.deleteNode(tim);
        });
      } else if (node.dataRef.children && node.dataRef.children.length > 0) {
        node.dataRef.children.forEach((tim) => {
          this.deleteNode(tim);
        });
      }
    },
    // 过滤出选中的节点
    setSelectUserList(nodes) {
      const selectList = []; // 保存选中的节点
      if (nodes) {
        nodes.forEach((tim) => {
          // 过滤用户user添加到右侧列表
          if (!this.selectListMap[tim.id] && tim.attributes && tim.attributes.nodeType === 'user') {
            const str = JSON.stringify(tim);
            const item = JSON.parse(str);
            selectList.push(item);
            this.selectListMap[tim.id] = item;
          }
        });
      }
      this.setDatatoSelectUser(selectList);
    },
    // 选中的节点放入selectUser 中
    setDatatoSelectUser(list) {
      this.selectUser.forEach((tim) => {
        if (tim.selectFlowTab === this.selectFlowTab) {
          // 暂时解决切换页签左侧值会出现重复的问题
          const ids = tim.users.map((item) => item.id);
          const arr = list.filter((node) => !ids.includes(node.id));
          if (this.checkable) {
            // 允许多选时追加选中用户
            tim.users = tim.users.concat(arr);
          } else {
            // 单选时直接设置
            tim.users = arr;
          }
        }
      });
    },
    /**
     * 把平台返回的tree数据转换成 ant.design tree数据
     * @param {*} data  原始数据
     * @param {*} scopedSlot   可通过 slot-scope 属性支持的属性
     * @param {*} scopedSlot   可通过 slot-scope 属性支持的属性
     */
    // eslint-disable-next-line max-params, @typescript-eslint/no-unused-vars, no-unused-vars
    processTreeData(data, nodeType, _scopedSlot = {}, custom) {
      const result = [];
      if (data && data.length > 0) {
        data.forEach((tim) => {
          const tree = {
            id: tim.id,
            nodeType: tim.nodeType ? tim.nodeType : nodeType,
            title: tim.name,
            key: tim.id,
            isLeaf: false,
            _parentId: this.defaultMaxParentId,
            disableCheckbox: false,
            disabled: false,
            selectable: true
            // checked: false
          };
          if (custom) {
            custom(tree);
          }
          result.push(tree);
        });
      }
      return result;
    },
    /** 获取额外的附件信息组合  */
    getAttributes(record) {
      let str = '';
      if (this.showMoreUserInfo && record.nodeType === 'user') {
        const values = [];
        if (typeof this.showMoreUserInfo == 'object' && this.showMoreUserInfo.length > 0) {
          for (let i = 0; i < this.showMoreUserInfo.length; i++) {
            if (record.attributes[this.showMoreUserInfo[i]]) {
              values.push(record.attributes[this.showMoreUserInfo[i]]);
            }
          }
        }
        if (values.length === 0) {
          const deptName = record.attributes && record.attributes.deptName ? record.attributes.deptName : '';
          if (deptName) {
            values.push(deptName);
          }
        }
        if (values.length > 0) {
          str = `(${values.join('/')})`;
        }
      }
      return str;
    },
    /**
     * 下拉框filterOption
     */
    filterOption(input, option) {
      return option.title.toLowerCase().indexOf(input.toLowerCase()) >= 0;
    },

    /**
     * 下拉框改变切换角色/群组/岗位
     */
    handleChange(value) {
      this.selectOptionId = value;
      // eslint-disable-next-line prefer-destructuring
      this.selectOption = this.treeData.filter((item) => item.id === value)[0];
      this.getUserList(this.selectOption);
    },
    /**
     * 快速查询逻辑
     * @param value 搜索框数据
     */
    handleKeyWordQuery(value) {
      // 用户走前端查询
      if (this.selectTag === 'user') {
        this.onSearch(value);
        return;
      }
      //  角色/岗位/群组走后端查询
      if (!this.selectOptionId) {
        this.$message.warning(`请选择${this.placeholderMap[this.selectTag]}`);
        return;
      }
      this.queryParam.searchParams.searchText = value;
      this.tableList = [];
      this.queryParam.pageParameter.page = 1;
      this.pagination.current = 1;
      this.getUserList(this.selectOption);
    },
    /**
     * 获取 角色/群组/岗位 用户分页列表
     */
    getUserList(node) {
      if (!this.selectOptionId) {
        this.$message.warning('请选择数据查询！');
      }
      this.$emit('loading', true);
      this.tableLoading = true;
      this.selectedRowKeys = [];
      // 获取查询参数
      this.queryParam.searchParams.filterUser = this.data.nextTask[this.selectFlowTab].currentActivityAttr.filterUser || '';
      this.queryParam.searchParams.secretLevel = this.data.secretLevel;
      this.queryParam.searchParams.currentTab = this.selectTag;
      this.queryParam.searchParams.id = this.selectOptionId;
      // // 默认展示已配置的角色/群组/岗位范围内所有用户
      // this.queryParam.searchParams.defaultLoadRoleId =
      //   this.selectTag === 'role' ? this.treeData.map((item) => item.id).join(',') : undefined;
      // this.queryParam.searchParams.defaultLoadGroupId =
      //   this.selectTag === 'group' ? this.treeData.map((item) => item.id).join(',') : undefined;
      // this.queryParam.searchParams.defaultLoadPositionId =
      //   this.selectTag === 'position' ? this.treeData.map((item) => item.id).join(',') : undefined;
      // this.queryParam.searchParams.id = this.selectOptionId || undefined;
      listCommonSelectUserByPage(this.queryParam)
        .then((res) => {
          if (res.success && res.data && res.data.result.length > 0) {
            // 处理数据格式
            res.data.result = this.formatData(res.data.result);
            this.pagination.total = res.data.pageParameter.totalCount;
            this.tableList = [...res.data.result];
            // 回显选中项数据
            this.setSelectedRowKeys();
          } else {
            this.selectedRowKeys = [];
            if (this.$objIsNotBlank(this.keyword)) {
              this.$message.warning(res.errorDesc || '未查询到匹配数据！');
            }
            if (res.errorDesc || node?.title) {
              this.$message.warning(res.errorDesc || `${node?.title ?? ''} 节点下无数据。`);
            }
            this.pagination.total = 0;
            this.tableList = [];
          }
        })
        .finally(() => {
          this.tableLoading = false;
          this.$emit('loading', false);
          this.updateCheckboxState();
        });
    },
    /**
     * 处理数据格式
     */
    formatData(list) {
      const newList = list.map((item) => {
        item.nodeType = 'user';
        item.key = item.id + this.$uuid(32);
        item.attributes.nodeType = 'user';
        return item;
      });
      return newList;
    },
    /**
     * 设置左侧侧角色/群组/岗位用户列表选中项
     */
    setSelectedRowKeys() {
      const selectedKeys = this.tableList.reduce((pre, cur) => {
        if (this.selectListMap[cur.id]) {
          pre.push(cur.key);
        }
        return pre;
      }, []);
      this.selectedRowKeys = [...selectedKeys];
    },
    /**
     * 当手动勾选并且值发生改变时触发的事件
     */
    onSelectChange(record, selected) {
      if (this.checkable) {
        const selectIds = Object.keys(this.selectListMap);
        if (selected) {
          // 选中
          if (!selectIds.includes(record.id)) {
            if (this.maxSelect > 0 && selectIds.length > this.maxSelect - 1) {
              this.$message.warning(`已设置最多选择${this.maxSelect}个角色！`);
            } else {
              this.setSelectUserList([record]);
              this.selectedRowKeys.push(record.key);
            }
          } else {
            this.selectedRowKeys.push(record.key);
          }
        } else {
          // 取消选中
          if (this.selectListMap[record.id]) {
            delete this.selectListMap[record.id];
            this.selectUser.forEach((tim) => {
              if (tim.selectFlowTab === this.selectFlowTab) {
                tim.users = Object.values(this.selectListMap);
              }
            });
            this.selectedRowKeys = this.selectedRowKeys.filter((key) => key.indexOf(record.id) === -1);
          }
        }
      } else {
        // 单选直接选中
        this.setSelectUserList([record]);
        this.selectedRowKeys = [record.key];
      }
      this.updateCheckboxState();
      this.$emit('changeSelectUser', this.selectUser);
    },
    /**
     * 点击行实现选中
     */
    handleRowSelection(record) {
      const selectIds = Object.keys(this.selectListMap);
      if (this.checkable) {
        // 多选
        if (!selectIds.includes(record.id)) {
          // 选中
          if (this.maxSelect > 0 && selectIds.length > this.maxSelect - 1) {
            this.$message.warning(`已设置最多选择${this.maxSelect}个角色！`);
          } else {
            this.setSelectUserList([record]);
            this.selectedRowKeys.push(record.key);
          }
        } else {
          // 取消选中
          if (this.selectListMap[record.id]) {
            delete this.selectListMap[record.id];
            this.selectUser.forEach((tim) => {
              if (tim.selectFlowTab === this.selectFlowTab) {
                tim.users = Object.values(this.selectListMap);
              }
            });
            this.selectedRowKeys = this.selectedRowKeys.filter((key) => key.indexOf(record.id) === -1);
          }
        }
      } else {
        // 单选直接选中
        this.selectListMap = {};
        this.setSelectUserList([record]);
        this.selectedRowKeys = [record.key];
        // if (!this.selectListMap[record.id]) {
        //   // 单选直接选中
        //   this.setSelectUserList([record]);
        //   this.selectedRowKeys = [record.key];
        // } else {
        //   this.selectListMap = {};
        //   this.selectUser.forEach((tim) => {
        //     if (tim.selectFlowTab === this.selectFlowTab) {
        //       tim.users = Object.values(this.selectListMap);
        //     }
        //   });
        //   this.selectedRowKeys = [];
        // }
      }
      this.updateCheckboxState();
      this.$emit('changeSelectUser', this.selectUser);
    },

    /**
     * 接收并处理分页、排序信息
     * @pagination,  分页信息
     */
    handleTableChange(paginationInfo) {
      if (this.selectTag !== 'user') {
        this.queryParam.pageParameter.page = paginationInfo.current; // 页数
        this.queryParam.pageParameter.rows = paginationInfo.pageSize; // 页数
        if (this.selectOptionId) {
          this.getUserList(this.selectOption);
        }
      }
    },
    // 全选
    handleCheckAllChange(e) {
      if (e.target.checked) {
        // 全选
        this.selectedRowKeys = this.tableList.map((item) => item.key);
        this.setSelectUserList(this.tableList);
      } else {
        // 取消全选
        this.selectedRowKeys = [];
        // 清空Map中的数据
        this.tableList.forEach((item) => {
          if (this.selectListMap[item.id]) {
            delete this.selectListMap[item.id];
          }
        });
        // 清空selectUser中的数据
        this.selectUser.forEach((tim) => {
          if (tim.selectFlowTab === this.selectFlowTab) {
            tim.users = Object.values(this.selectListMap);
          }
        });
      }
      this.updateCheckboxState();
      this.$emit('changeSelectUser', this.selectUser);
    },
    updateCheckboxState() {
      if (this.selectedRowKeys.length > 0) {
        if (this.selectedRowKeys.length !== this.tableList.length) {
          this.state.checkAll = false;
        } else if (this.selectedRowKeys.length === this.tableList.length) {
          this.state.checkAll = true;
        }
      } else {
        this.state.checkAll = false;
      }
    }
  }
};
</script>
<style lang="less" scoped>
.select-role-box {
  position: relative;
  .pagination-box {
    position: absolute;
    bottom: 5px;
    left: 7px;
  }
  :deep(.surely-table-wrapper) {
    .surely-table-pagination {
      margin: 4px;
    }
  }
}
</style>
